<?php
namespace app\index\controller;
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods:POST,GET");

use app\common\controller\HomeBase;

use think\Db;

class Insurance extends HomeBase
{
	protected function _initialize(){
		parent::_initialize();
	}
	/**
	*保险首页(能够办理的保险)
	*@param  int id 		  保险的id
	**/
	public function index()
	{
		$id = $_GET['id'];
		$list = Db('nav')->where('pid',$id)->page(1,8)->select();
		$this->doif($list);
	}

	/**
	*申请办理添加显示需要添加的材料
	*@param  int id 		  办理具体哪家保险的id
	**/
	public function insuranceAddShow()
	{
		$id = $_GET['id'];
		$list = Db('nav')->where('id',$id)->select();
		$this->doif($list);
	}

	/**
	*申请办理添加操作
	*@param  int nav_id   办理具体哪家保险的nav_id
	*@param  int id 	  保险的id
	**/
	public function reserveadd()
	{
		$classifyID = $_POST['id'];
		$nav_id = $_POST['nav_id'];
		$name = htmlspecialchars($_POST['name']);
		$phone = htmlspecialchars($_POST['phone']);
		$content= htmlspecialchars($_POST['content']);

		//判断该手机号是否申请过
		$number = Db('reserved')->where('nav_id',$nav_id)->where('reservedPhone',$phone)->find();
		if ($number) {
			$this->apiError('已申请该保险,请您耐心等待');
			die;
		}

		// 获取表单上传文件
		$files = request()->file('file');
		if ($files) {
			foreach($files as $file){
				// 移动到框架应用根目录/public/uploads/ 目录下
				$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
				if($info){
					// 成功上传后 将成功的文件名存入数组
					$arr[] = $info->getFilename();
					
				}else{
					// 上传失败获取错误信息
					echo $file->getError('图片添加失败,请重试');
				}
			}
			//遍历拼接数组名字
			foreach($arr as $photoName){
				$data = date('Ymd',strtotime('now'));
				$path = '/uploads/'.$data.'/'.$photoName;
				$photo[] = $path;
			}

			//将数组序列化之后存入数据库
			$photo = serialize($photo);
		}else{
			$photo = '';
		}
		$reservedDate = date('Y-m-d H:i:s',strtotime('now'));
		$data = [
			'classifyID'=>$classifyID,
			'nav_id'=>$nav_id,
			'reservedName'=>$name,
			'reservedPhone'=>$phone,
			'reservedDate'=>$reservedDate,
			'photo'=>$photo,
			'content'=>$content
		];
		$add = Db('reserved')->insert($data);
		if($add){
			//添加成功之后返回公司的电话号码
			$phoneList = Db('system')->select();
			$value = unserialize($phoneList[0]['value']);
			$arr[] = $value['site_phone'];
			$this->apiSuccess($arr,'添加成功');
		}else{
			$this->apiError('添加失败,请重试');
		}
	}
	public function doif($arr)
	{
		if($arr){
            $this->apiSuccess($arr);
        }else{
            $this->apiError('没有查到信息');
        }
	}

}